<template>
  <el-card :shadow="'never'">
    <div class="flex">
      <div class="demo-datetime-picker">
        <div class="block">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            start-placeholder="Start date"
            end-placeholder="End date"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY/MM/DD ddd"
            time-format="A hh:mm:ss"
            value-format="YYYY-MM-DD hh:mm:ss"
            @change="handleConfirm"
            unlink-panels
          />
        </div>
      </div>
    </div>
    <el-button
      type="success"
      bg
      size="large"
      @click="updateTime"
      style="margin-left: 45%; margin-top: 50px"
      >修改</el-button
    >
  </el-card>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import * as $accountApi from "@/api/sci/account";
import { ElMessage, ElMessageBox } from "element-plus";

// 当前选中的节点ID
const form = reactive({
  id: "",
  start_time: "",
  end_time: ""
});

// 显式地声明 timeRange 的类型为 [Date, Date] 或者 null
const timeRange = ref<[Date | null, Date | null]>([null, null]);

// 确认选择后的处理
const handleConfirm = () => {
  const [start, end] = timeRange.value;
  form.start_time = start ? start.toString() : "";
  form.end_time = end ? end.toString() : "";
};

const _getTime = () => {
  $accountApi
    .getTime()
    .then((res: any) => {
      if (res.success) {
        form.id = res.result.id;
        form.start_time = res.result.start_time;
        timeRange.value[0] = res.result.start_time;
        form.end_time = res.result.end_time;
        timeRange.value[1] = res.result.end_time;
      }
    })
    .finally(() => {});
  $accountApi
    .checkTime()
    .then((res: any) => {
      if (res.success) {
        console.log(res.result);
      }
      console.log(res);
    })
    .catch(() => {});
};
onMounted(() => {
  _getTime();
});
// 加载数据
const updateTime = () => {
  ElMessageBox.confirm("确认设定该时间范围?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      _updateTime();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消"
      });
    });
};
const _updateTime = () => {
  $accountApi
    .updateTime(form)
    .then((res: any) => {
      if (res.success) {
        ElMessage({
          message: "更新成功",
          type: "success"
        });
      }
    })
    .finally(() => {
      _getTime();
    });
};
</script>
<style lang="css" scoped>
.flex {
  display: flex;
  justify-content: center;
}

.demo-datetime-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: stretch;
}
.demo-datetime-picker .block {
  padding: 30px 0;
  text-align: center;
}
.line {
  width: 1px;
  background-color: var(--el-border-color);
}
</style>
